package com.leetcode;

import java.util.Arrays;

/**
 * 16. 最接近的三数之和
 * 排序 + 对撞指针 + abs
 *
 * @author fy
 * @date 2022/4/8 9:19
 */
public class Solution16 {

    public int threeSumClosest(int[] nums, int target) {
        if (nums == null || nums.length < 3) {
            throw new IllegalArgumentException("error nums");
        }
        int n = nums.length;
        Arrays.sort(nums);
        int min = Integer.MAX_VALUE;
        int res = 0;
        for (int i = 0; i < n; i++) {
            int p = i + 1;
            int q = n - 1;
            int t = target - nums[i];
            while (p < q) {
                int diff = t - (nums[p] + nums[q]);
                if (min > Math.abs(diff)) {
                    min = Math.abs(diff);
                    res = nums[i] + nums[p] + nums[q];
                }
                if (diff == 0) {
                    return target;
                } else if (diff > 0) {
                    p++;
                } else {
                    q--;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{-1, 2, 1, -4};
        int target = 1;
        int res = new Solution16().threeSumClosest(nums, target);
        System.out.println(res);
    }
}
